<?php
namespace app\erp_meixingtiyu\model;

use think\Model;
use think\model\concern\SoftDelete;
use app\erp_meixingtiyu\model\Arena as ArenaModel;

class ArenaPart extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $table = 'athlon_arena_part';
    protected $pk = 'arena_part_id';

    public function fragments()
    {
        return $this->belongsToMany(
            TimeFragment::class,
            ArenaPartTimeFragment::class
        );
    }

    public function bookings()
    {
        return $this->hasManyThrough(
            Booking::class,
            ArenaPartTimeFragment::class
        );
    }

    public function arena()
    {
        return $this->belongsTo(Arena::class);
    }

    public function sessions()
    {
        return $this->hasMany(ArenaPartTimeFragment::class);
    }

    public static function getPaginatePartsByArenaId($arenaId)
    {
        return self::with('arena')
            ->where('arena_id', $arenaId)
            ->order('sort asc')
            ->paginate(15);
    }

    public function createPartWithTimeFragments($params)
    {
        $this->transaction(function () use ($params) {
            // 新增半场
            $part = self::create($params);

            // 判断该时段模板下是否有设置时间段
            $arena = ArenaModel::with('timeTemplate.fragments')->find(
                $params['arena_id']
            );
            $timeTemplate = $arena->timeTemplate;
            // 若该模板下有设置时段，则和新建的半场关联
            if (!$timeTemplate->fragments->isEmpty()) {
                // 获取该模板下所有时段id
                $fragments = array_map(function ($val) {
                    return $val['time_fragment_id'];
                }, $timeTemplate->fragments->toArray());
                // 关联所有时段，设置半场的初始状态、初始价格和排序
                $part->fragments()->attach($fragments, [
                    'status' => $timeTemplate->status,
                    'price' => $timeTemplate->price,
                    'sort' => $timeTemplate->sort,
                ]);
            }
        });
    }

    public function deletePartWithFragmentsById($partId)
    {
        $this->transaction(function () use ($partId) {
            $part = $this->find($partId);
            // 删除该半场与时段的所有关联
            $part->fragments()->detach($part->fragments);
            // 删除半场
            $part->delete();
        });
    }
}
